package com.baizhi.cmfz.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baizhi.cmfz.annotation.LogAnnotation;
import com.baizhi.cmfz.entity.Guru;
import com.baizhi.cmfz.service.GuruService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("guru")
public class GuruController {
    @Autowired
    private GuruService guruService;

    //分页展示上师信息
    @RequestMapping("all")
    @LogAnnotation(value = "查找所有上师")
    public Map selectAllGuru(int page, int limit, String guruName) {
        return guruService.selectAllGuru(page, limit, guruName);
    }

    @RequestMapping("allGuru")
    public List<Guru> showAllGuru() {
        return guruService.showAll();
    }

    //添加上师信息
    @RequestMapping("add")
    @LogAnnotation(value = "添加上师", type = "insert")
    public boolean addGuru(Guru guru, HttpServletRequest request, MultipartFile file) {
        if (file != null) {
            //设置文件名
            String oldFileName = file.getOriginalFilename();
            String fileName = "/img/" + new Date().getTime() + "_" + oldFileName;
            //上传路径
            String path = request.getServletContext().getRealPath("/");
            //用流复制
            try {
                file.transferTo(new File(path + fileName));
                guru.setGuruImage(fileName);
                guruService.addGuru(guru);
                return true;
            } catch (IOException e) {
                return false;
            }
        } else {
            return guruService.addGuru(guru) > 0;
        }
    }

    //更改上师信息
    @RequestMapping("update")
    @LogAnnotation(value = "更改上师信息", type = "update")
    public boolean updateGuru(Guru guru, HttpServletRequest request, MultipartFile file) {
        if (file != null) {
            //设置文件名
            String oldFileName = file.getOriginalFilename();
            String fileName = "/img/" + new Date().getTime() + "_" + oldFileName;
            //上传路径
            String path = request.getServletContext().getRealPath("/");
            //用流复制
            try {
                file.transferTo(new File(path + fileName));
                guru.setGuruImage(fileName);
                guruService.updateGuru(guru);
                return true;
            } catch (IOException e) {
                return false;
            }
        } else {
            return guruService.updateGuru(guru) > 0;
        }
    }

    //冻结上师
    @RequestMapping("freeze")
    @LogAnnotation(value = "改变上师状态", type = "update")
    public boolean freeze(Guru guru) {
        return guruService.updateGuru(guru) > 0;
    }

    //删除上师信息
    @RequestMapping("remove")
    @LogAnnotation(value = "删除上师", type = "delete")
    public boolean removeGuru(int[] ids) {
        return guruService.removeGuru(ids) > 0;
    }

    //查找上师信息
    @RequestMapping("selectOne")
    @LogAnnotation(value = "根据id查找上师")
    public Guru selectOneGuru(int guruId) {
        return guruService.selectOneGuru(guruId);
    }

    //下载excel
    @RequestMapping("down")
    @LogAnnotation(value = "导出Excel文件，下载所有上师信息表")
    public void guruDown(HttpServletResponse response) throws IOException {
        ExportParams exportParams = new ExportParams("所有上师信息", "guru");
        List<Guru> gurus = guruService.showAll();
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, Guru.class, gurus);
        //设置文件格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //设置文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("上师信息表.xlsx", "UTF-8"));
        //保存在本地
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        }
    }

    //上传excel
    @RequestMapping("upload")
    @LogAnnotation(value = "上传Excel文件，批量添加上师信息", type = "insert")
    public Map<String, Object> guruUpload(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setNeedSave(true);
        List<Guru> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), Guru.class, params);
            list.forEach(guru -> guruService.addGuru(guru));
        } catch (Exception e) {
            map.put("code", 1);
            map.put("msg", "上传失败");
        }
        assert list != null;
        list.forEach(System.out::println);

        map.put("code", 0);
        map.put("msg", "上传成功");
        return map;
    }
    /*//文件上传
    @RequestMapping("upload")
    public Map upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpSession session) throws
     IOException {
        Map<String, Object> map = new HashMap<>();
        //设置文件名
        String oldFileName = file.getOriginalFilename();
        String fileName = "/img/" + new Date().getTime() + "_" + oldFileName;
        //上传路径
        String path = session.getServletContext().getRealPath("/");
        //用流复制
        file.transferTo(new File(path + fileName));
        map.put("code", 0);
        map.put("msg", "上传成功");
        session.setAttribute("guruImg", fileName);
        return map;
    }*/
}
